package com.endurance.decorate.ext;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.endurance.decorate.AbstractDecorateCache;
import com.endurance.decorate.impl.JVMCache;
import com.endurance.pojo.UserEntity;
import com.endurance.utils.RedisUtils;
import org.aspectj.lang.ProceedingJoinPoint;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

/**
 * @Author: sunlin
 * @Date: 2024-05-16 18:03
 * @Version: 1.0
 * @Description: 使用Redis作为二级缓存  装饰类需要实现自己的接口，装饰类可能也会有自己的需求
 */
@Component
public class RedisDecorateCache extends JVMCache implements AbstractDecorateCache {

    @Autowired
    private RedisUtils redisUtils;

    @Override
    public <T> T getCache(String key, Class<T> t, ProceedingJoinPoint joinpoint) {
        // 从二级缓存中获取数据
        T redisUser = JSONObject.parseObject(redisUtils.get(key), t);
        if (redisUser != null) {
            return (T) redisUser;
        }
        // 从一级缓存中获取数据
        T JVMCacheUser = super.getCache(key, t, joinpoint);

        if (JVMCacheUser == null) {
            return null;
        }
        redisUtils.set(key, JSON.toJSONString(JVMCacheUser));
        return (T) JVMCacheUser;
    }

}
